<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta http-equiv="X-UA-Compatible" content="ie=edge"/>
    <title>Document</title>
    <script>const http = require('http')
const path = require('path')
const fs = require('fs')
const promisify = require('util').promisify

const stat = promisify(fs.stat)
const readdir = promisify(fs.readdir)

const CONFIG = require('./config/defaultConfig.js')

const server = http.createServer((req, res) => {
  const filePath = path.join(CONFIG.root, req.url)

  fnRoute(req, res, filePath)
  
}).listen(CONFIG.port)

let fnRoute = async (req, res, filePath) => {
  const stats = await stat(filePath)
  try {
    if(stats.isFile()) {
      res.writeHeader(200, {
        'content-type': 'text/plain;charset=utf-8'
      })
      fs.createReadStream(filePath).pipe(res)
    } else if(stats.isDirectory()){
      fnReadDir(req, res, filePath)
      
    }
  } catch (error) {
    res.writeHeader(404, {
      'content-type': 'text/html'
    })
    res.write('<h2>抱歉，您请求的地址不存在!!!</h2>')
  }
}

let fnReadDir = async (req, res, filePath) => {
  const files = await readdir(filePath)
  try {
    res.writeHeader(200, {
      'content-type': 'text/html;charset=utf-8'
    })
    let html = ''
    files.map((item, i) => {
      html += `<div><a>${item}  </a></div>`
    })
    res.end(html)
  } catch (error) {
    console.log(error)
  }
}
    </script>
  </head>
  <body>
    <script src="../hello.js"></script>
    <div style="width:100px; height:100px; background:red;">hello jade</div>
    <div style="width:200px;height:400px;background:blue;">hello jade</div>
    <div class="aaa bbb"></div>victor
  </body>
</html>